package com.gdufe.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.common.entity.User;
import com.gdufe.common.utils.PageUtils;
import com.gdufe.common.utils.Query;
import com.gdufe.common.vo.AddPointsVo;
import com.gdufe.user.dto.PasswordDto;
import com.gdufe.user.mapper.UserMapper;
import com.gdufe.user.service.UserClientService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
public class UserClientServiceImpl extends ServiceImpl<UserMapper, User> implements UserClientService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<User> page = this.page(
                new Query<User>().getPage(params),
                new QueryWrapper<User>()
        );

        return new PageUtils(page);
    }

    //用户支付订单后获得积分
    @Override
//    @Transactional
    public void addPoints(AddPointsVo vo) {
        User user = this.getById(vo.getUserId());
        int p = user.getPoint();
        user.setPoint(p + vo.getPoints());
        int newPoint = user.getPoint();
        switch (newPoint / 50) {
            case 0:
                break;
            case 1:
                user.setLevel(1);
                break;
            case 2:
                user.setLevel(2);
                break;
            default:
                user.setLevel(3);
        }
        this.updateById(user);
    }

    /**
     * 获取登录的用户信息
     *
     * @return
     */
    public User getClientUser() {
        //获取当前线程的请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        String[] auth = authorization.split(" ");
        String token = auth[1];
        Long userId = null;
        if (!StrUtil.isBlank(token)) {
            userId = JWT.decode(token).getClaim("user_id").asLong();
        }
        return getById(userId);
    }

    /**
     * 修改密码
     *
     * @param passwordDto
     */
    @Override
    public void editPassword(PasswordDto passwordDto) {
        //获取当前登录的用户信息
        User user = getClientUser();
        //获取新密码
        String newPassword = passwordDto.getNewPassword();
        //加密
        user.setPassword(new BCryptPasswordEncoder().encode(newPassword));
        //更新密码
        updateById(user);
    }
}
